package com.manage.common.log.aspect;

import cn.hutool.json.JSONUtil;
import com.manage.common.core.dto.token.User;
import com.manage.common.core.utils.ContextHolderUtils;
import com.manage.common.core.utils.CusAccessObjectUtil;
import com.manage.common.core.utils.IPAddressUtils;
import com.manage.common.core.utils.StringUtils;
import com.manage.common.log.annotation.OperateLog;
import com.manage.common.log.context.SpringContextHolder;
import com.manage.common.log.event.SysOperateLogEvent;
import com.manage.system.api.entity.SysOperateLog;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author zhangqing
 * @version V1.0
 * @description 操作日志记录aop
 * @date 6/3/2021 12:49 PM
 */
@Aspect
@Slf4j
@Component
public class OperateLogAspect {

    /**
     * 配置织入点为OperateLog注解
     */
    @Pointcut("@annotation(com.manage.common.log.annotation.OperateLog)")
    public void logPointCut() {
    }

    /**
     * 处理完请求后执行
     *
     * @param joinPoint 切点
     */
    @AfterReturning(pointcut = "logPointCut()")
    public void doAfterReturning(JoinPoint joinPoint) {
        handleLog(joinPoint, null);
    }

    /**
     * 拦截异常操作
     *
     * @param joinPoint 切点
     * @param e         异常
     */
    @AfterThrowing(value = "logPointCut()", throwing = "e")
    public void doAfterThrowing(JoinPoint joinPoint, Exception e) {
        handleLog(joinPoint, e);
    }

    private void handleLog(final JoinPoint joinPoint, final Exception e) {
        try {
            // 获得注解
            OperateLog controllerLog = getAnnotationLog(joinPoint);
            if (controllerLog == null) {
                return;
            }
            // *========数据库日志=========*//
            SysOperateLog sysOperateLog = new SysOperateLog();
            sysOperateLog.setStatus(Boolean.TRUE);
            // 请求的地址
            HttpServletRequest request = ContextHolderUtils.getRequest();
            String ip = CusAccessObjectUtil.getIpAddress(request);
            sysOperateLog.setOperatorIp(ip);
            sysOperateLog.setOperatorUrl(request.getRequestURI());
            sysOperateLog.setOperatorLocation(IPAddressUtils.getRealAddress(ip));
            User currentUser = ContextHolderUtils.getCurrentUser();
            sysOperateLog.setOperator(currentUser.getUserName());
            if (e != null) {
                sysOperateLog.setStatus(Boolean.FALSE);
                sysOperateLog.setErrorMsg(StringUtils.substring(e.getMessage(), 0, 2000));
            }
            // 设置方法名称
            String className = joinPoint.getTarget().getClass().getName();
            String methodName = joinPoint.getSignature().getName();
            sysOperateLog.setMethodLink(className + "." + methodName + "()");
            // 设置请求方式
            sysOperateLog.setRequestType(request.getMethod());
            // 处理设置注解上的参数
            Object[] args = joinPoint.getArgs();
            getControllerMethodDescription(controllerLog, sysOperateLog, args);
            // 发布事件
            SpringContextHolder.publishEvent(new SysOperateLogEvent(sysOperateLog));
        } catch (Exception exp) {
            // 记录本地异常日志
            log.error("==前置通知异常==");
            log.error("异常信息:{}", exp.getMessage());
            exp.printStackTrace();
            throw new RuntimeException(exp.getMessage());
        }
    }

    private void getControllerMethodDescription(OperateLog operateLog, SysOperateLog sysOperateLog, Object[] args) throws Exception {
        // 设置action动作
        sysOperateLog.setBusinessType(String.valueOf(operateLog.businessType().ordinal()));
        // 设置模块
        sysOperateLog.setModule(operateLog.module());
        // 设置标题
        sysOperateLog.setTitle(operateLog.title());
        // 设置操作人类别
        sysOperateLog.setOperatorType(String.valueOf(operateLog.operatorType().ordinal()));
        // 是否需要保存request，参数和值
        if (operateLog.isSaveRequestData()) {
            // 获取参数的信息，传入到数据库中。
            setRequestValue(sysOperateLog, args);
        }
    }

    private void setRequestValue(SysOperateLog sysOperateLog, Object[] args) {
        List<?> param = new ArrayList<>(Arrays.asList(args)).stream().filter(p -> !(p instanceof ServletResponse))
                .collect(Collectors.toList());
        log.debug("args:{}", param);
        String params = JSONUtil.toJsonStr(param);
        sysOperateLog.setOperatorParam(StringUtils.substring(params, 0, 2000));
    }


    /**
     * 是否存在注解，如果存在就获取
     */
    private OperateLog getAnnotationLog(JoinPoint joinPoint) {
        Signature signature = joinPoint.getSignature();
        MethodSignature methodSignature = (MethodSignature) signature;
        Method method = methodSignature.getMethod();
        if (method != null) {
            return method.getAnnotation(OperateLog.class);
        }
        return null;
    }
}
